package com.zfzs.post.service.impl;

import com.zfzs.post.common.bean.CommonConst;
import com.zfzs.post.common.utils.AgentType;
import com.zfzs.post.common.utils.MerchantType;
import com.zfzs.post.enums.DayType;
import com.zfzs.post.exception.BadRequestException;
import com.zfzs.post.model.dto.*;
import com.zfzs.post.model.vo.*;
import com.zfzs.post.modules.agent.domain.Agent;
import com.zfzs.post.modules.agent.domain.AgentVerified;
import com.zfzs.post.modules.agent.service.AgentService;
import com.zfzs.post.modules.agent.service.AgentVerifiedService;
import com.zfzs.post.modules.agent.service.dto.AgentDTO;
import com.zfzs.post.modules.common.domain.AgentContact;
import com.zfzs.post.modules.common.service.AgentContactService;
import com.zfzs.post.modules.common.service.AgentTreeService;
import com.zfzs.post.modules.goods.domain.GoodOrder;
import com.zfzs.post.modules.goods.service.GoodOrderService;
import com.zfzs.post.modules.goods.service.GoodOrderSnService;
import com.zfzs.post.modules.merchant.service.MerchantService;
import com.zfzs.post.modules.policy.domain.Policy;
import com.zfzs.post.modules.policy.domain.PolicyKind;
import com.zfzs.post.modules.policy.domain.PolicyType;
import com.zfzs.post.modules.policy.domain.PolicyTypeInfo;
import com.zfzs.post.modules.policy.service.PolicyInfoService;
import com.zfzs.post.modules.policy.service.PolicyTypeService;
import com.zfzs.post.modules.post.service.TerminalInfoService;
import com.zfzs.post.modules.transaction.service.BenefitDayService;
import com.zfzs.post.modules.transaction.service.TransactionInfoService;
import com.zfzs.post.page.JpaPageHelper;
import com.zfzs.post.service.*;
import com.zfzs.post.utils.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.NumberFormat;
import java.util.*;

/**
 * 首页实现类
 *
 * @author: ck
 * @create: 2019-08-13 16:46
 **/
@Service
public class IndexServiceImpl implements IndexService {

    @Autowired
    private AgentContactService agentContactService;
    @Autowired
    private JwtUserDetailsService jwtUserDetailsService;
    @Autowired
    private AgentService agentService;
    @Autowired
    private GoodOrderService goodOrderService;
    @Autowired
    private MerchantService merchantService;
    @Autowired
    private TransactionInfoService transactionInfoService;
    @Autowired
    private AgentVerifiedService verifiedService;
    @Autowired
    private GoodOrderSnService goodOrderSnService;
    @Autowired
    private PolicyInfoService policyInfoService;
    @Autowired
    private PolicyTypeService policyTypeService;
    @Autowired
    private AgentVerifiedService agentVerifiedService;
    @Autowired
    private BenefitDayService benefitDayService;
    @Autowired
    private TerminalInfoService terminalService;

    @Override
    public Map<String, Object> getIndexTopInfo(DateTypeDTO dto) {
        Map<String, Object> map = new HashMap<>();
        //获取登录人id
        AgentDTO agent = jwtUserDetailsService.getAgentInfo();
        Long channelId = agent.getChannelId();
        Long id = agent.getId();
        String dateType = dto.getDateType();
        String endDate = dto.getEndDate();
        String startDate = dto.getStartDate();
        //获取合伙人id
        List<Long> ids = agentContactService.findAllTeamIds(id, channelId);
        if (StringUtils.isNotEmpty(dateType)) {
            Map<String, String> day = DateStrUtils.getStartAndEndDate(dateType);
            if (day == null) {
                throw new BadRequestException("维度类型参数错误");
            }
            startDate = day.get("startDate");
            endDate = day.get("endDate");
        } else {
            throw new BadRequestException("维度类型参数错误");
        }

        //流水统计
        BigDecimal transactionSum = transactionInfoService.querySumByAgentIds(channelId, ids, startDate, endDate);
        map.put("transactionSum", MathUtils.formatToNumber(transactionSum));
        //采购新增
        int goodsBuyCount = goodOrderService.queryCountByAgentIds(channelId, ids, startDate, endDate);
        map.put("goodsBuyCount", goodsBuyCount);
        //商户新增
        int merchantCount = merchantService.queryCountByAgentIds(ids, startDate, endDate);
        map.put("merchantCount", merchantCount);
        //团队新增
        int agentCount = agentService.queryCountByAgentIds(channelId, agentContactService.findAllTeamIdsExceptSelf(id, channelId), startDate, endDate);
        map.put("agentCount", agentCount);
        return map;
    }

    @Override
    public Map<String, Object> getShopAddList(DateTypeDTO dto) {
        Map<String, Object> map = new HashMap<>();
        //获取登录人id
        AgentDTO agent = jwtUserDetailsService.getAgentInfo();
        Long channelId = agent.getChannelId();
        Long id = agent.getId();
        //开始时间  结束时间
        String startDate = dto.getStartDate();
        String endDate = dto.getEndDate();
        if (StringUtils.isBlank(startDate) || StringUtils.isBlank(endDate)) {
            //默认本月时间
            Map<String, String> day = DateStrUtils.getStartAndEndDate(DayType.TO_MONTH);
            if (day == null) {
                throw new BadRequestException("维度类型参数错误");
            }
            startDate = day.get("startDate");
            endDate = day.get("endDate");
        }
        //自营
        List<Long> selfIds = new ArrayList<>();
        selfIds.add(id);
        //自营 直营 合伙人
        List<AgentType> list = AgentType.getAgentTypeList();
        for (int i = 0; i < list.size(); i++) {
            List<Long> ids = new ArrayList<>();
            String type = list.get(i).getType();
            switch (type) {
                case "self":
                    ids.add(id);
                    break;
                case "partner":
                    ids = agentContactService.findPartnerTeam(id, channelId);
                    break;
                case "direct":
                    ids = agentContactService.findDirectlyIds(id, channelId);
                    break;
            }
            QuerTypePageDTO query = new QuerTypePageDTO();
            query.setChannelId(channelId);
            query.setEndDate(endDate);
            query.setIds(ids);
            query.setPageNum(0);
            query.setStartDate(startDate);
            query.setPageSize(5);
            JpaPageHelper page = goodOrderService.queryOrderByAgentIds(query);
            list.get(i).setList(page.getResult());
            //计算总的数据
            int totalCount = goodOrderService.queryOrderByAgentIdsSum(channelId, ids, startDate, endDate);
            list.get(i).setTotalCount(totalCount);
        }
        map.put("list", list);
        return map;
    }

    @Override
    public Map<String, Object> getShopAddInfoPage(QueryPageDateTypeDTO dto) {
        Map<String, Object> map = new HashMap<>();
        //获取登录人id
        AgentDTO agent = jwtUserDetailsService.getAgentInfo();
        Long channelId = agent.getChannelId();
        Long id = agent.getId();
        //开始时间  结束时间
        String startDate = dto.getStartDate();
        String endDate = dto.getEndDate();
        //默认时间
        if (StringUtils.isBlank(endDate) || StringUtils.isBlank(startDate)) {
            //默认本月时间
            Map<String, String> day = DateStrUtils.getStartAndEndDate(DayType.TO_MONTH);
            if (day == null) {
                throw new BadRequestException("维度类型参数错误");
            }
            startDate = day.get("startDate");
            endDate = day.get("endDate");
        }
        String type = dto.getType();
        int pageNum = dto.getPageNum();
        int pageSize = dto.getPageSize();
        List<Long> ids = new ArrayList<>();
        switch (type) {
            case "self":
                ids.add(id);
                break;
            case "partner":
                ids = agentContactService.findPartnerTeam(id, channelId);
                break;
            case "direct":
                ids = agentContactService.findDirectlyIds(id, channelId);
                break;
        }
        //封装参数
        QuerTypePageDTO query = new QuerTypePageDTO();
        query.setChannelId(channelId);
        query.setEndDate(endDate);
        query.setIds(ids);
        query.setPageNum(pageNum);
        query.setStartDate(startDate);
        query.setPageSize(pageSize);
        JpaPageHelper page = goodOrderService.queryOrderByAgentIds(query);
        map.put("page", page);
        return map;
    }

    @Override
    public Map<String, Object> getShopAddInfo(QueryGoodsInfoDTO dto) {
        Map<String, Object> map = new HashMap<>();
        //获取登录人id
        AgentDTO agent = jwtUserDetailsService.getAgentInfo();
        Long channelId = agent.getChannelId();
        Long id = agent.getId();
        String orderNo = dto.getOrderNo();
        List<QueryShopInfo> terminalList = goodOrderSnService.querySntByorderNoList(orderNo, channelId);
        for (int i = 0; i < terminalList.size(); i++) {
            AgentVerified verified = agentVerifiedService.findById(id);
            terminalList.get(i).setAgentName(verified.getCardName());
        }
        map.put("terminalList", terminalList);
        //客户经理
        map.put("agnetId", id);
        //客户经理姓名
        AgentVerified v = agentVerifiedService.findById(id);
        map.put("cardName", v.getCardName());
        GoodOrder order = goodOrderService.findByOrderNo(orderNo);
        //采购数量
        map.put("number", order.getGoodsNum());
        //采购时间
        map.put("createDate", DateStrUtils.formatDate(order.getCreateDate(), DateStrUtils.Y_M_D));
        //返现政策查询
        PolicyType policyType = policyTypeService.findbyPolicyTypeName("返现政策");
        if (policyType == null) {
            map.put("backPolic", "-");
        } else {
            PolicyKind policyKind = policyInfoService.findPolicy(id, order.getTerminalTypeId(), policyType.getId());
            if (policyKind == null) {
                map.put("backPolic", "-");
            } else {
                List<Policy> list = policyKind.getPolicyList();
                List<PolicyVO> policyList = CloneUtils.batchClone(list, PolicyVO.class);
                String backPolic = "";
                if (policyList.size() > 0) {
                    for (int i = 0; i < policyList.size(); i++) {
                        String policyTypeId = policyList.get(i).getPolicyTypeId();
                        PolicyTypeInfo policyTypeInfo = policyTypeService.queryPolicyTypeInfo(policyKind.getId(), policyTypeId);
                        String name = policyTypeInfo.getName();
                        String unit = policyTypeInfo.getUnit();
                        String amount = policyList.get(i).getAmount();
                        backPolic += name + "：" + amount + unit + "\n";
                    }
                    backPolic = backPolic.substring(0, backPolic.length() - 1);
                } else {
                    backPolic = "=";
                }
                map.put("backPolic", backPolic);
            }
        }
        //到期时间
        map.put("invalidDate", "2019-10-02");
        return map;
    }

    @Override
    public Map<String, Object> getIndexBottomInfo(DateTypeDTO dto) {
        Map<String, Object> map = new HashMap<>();
        String dateType = dto.getDateType();
        String endDate = dto.getEndDate();
        String startDate = dto.getStartDate();
        String manageType = dto.getManageType();
        if (StringUtils.isEmpty(dateType)) {
            throw new BadRequestException("维度类型参数错误");
        }
        if (StringUtils.isNotEmpty(dateType)) {
            Map<String, String> day = DateStrUtils.getStartAndEndDate(dateType);
            if (day == null) {
                throw new BadRequestException("维度类型参数错误");
            }
            startDate = day.get("startDate");
            endDate = day.get("endDate");
        } else {
            throw new BadRequestException("维度类型参数错误");
        }
        //模拟数据 封装数据
        List<StatisticalVO> statisticalList = new ArrayList<>();
        StatisticalVO vo = new StatisticalVO();
        vo.setName("分润");
        vo.setActivName("激活");
        vo.setActivRatio("26");
        vo.setNoActivRatio("74");
        vo.setNoActivRatioName("未激活");
        statisticalList.add(vo);

        StatisticalVO vo1 = new StatisticalVO();
        vo1.setName("激活率");
        vo1.setActivName("激活");
        vo1.setActivRatio("30");
        vo1.setNoActivRatio("70");
        vo1.setNoActivRatioName("未激活");
        statisticalList.add(vo1);

        map.put("list", statisticalList);
        return map;
    }

    @Override
    public Map<String, Object> getIndexBottomChart(DateTypeDTO dto) {
        Map<String, Object> map = new HashMap<>();
        AgentDTO agent = jwtUserDetailsService.getAgentInfo();
        Long channelId = agent.getChannelId();
        Long id = agent.getId();
        String dateType = dto.getDateType();
        String endDate = dto.getEndDate();
        String startDate = dto.getStartDate();
        String manageType = dto.getManageType();
        List<ChartVO> list = new ArrayList<>();
        if (StringUtils.isEmpty(dateType)) {
            throw new BadRequestException("维度类型参数错误");
        }
        if (StringUtils.isEmpty(manageType)) {
            throw new BadRequestException("查询类型不能为空");
        }
        if (StringUtils.isNotEmpty(dateType)) {
            Map<String, String> day = DateStrUtils.getStartAndEndDate(dateType);
            if (day == null) {
                throw new BadRequestException("维度类型参数错误");
            }
            startDate = day.get("startDate");
            endDate = day.get("endDate");
        } else {
            throw new BadRequestException("维度类型参数错误");
        }
        // 管理类型  0：业务  1：客户 2：团队 3：设备
        switch (manageType) {
            case "0":
                list = getYeWuCharList(startDate, endDate, id, channelId);
                break;
            case "1":
                list = getTuanDuiCharList(startDate, endDate, id, channelId);
                break;
            case "2":
                list = getSheBeiCharList(startDate, endDate, id, channelId);
                break;
            case "3":
                list = getKeHuCharList(startDate, endDate, id, channelId);
                break;
        }
        map.put("list", list);
        return map;
    }

    @Override
    public Map<String, Object> getTransactionSum(DateTypeDTO dto) {
        Map<String, Object> map = new HashMap<>();
        //开始时间
        String startDate = dto.getStartDate();
        //结束时间
        String endDate = dto.getEndDate();
        if (StringUtils.isBlank(startDate) || StringUtils.isBlank(endDate)) {
            //默认本月时间
            Map<String, String> day = DateStrUtils.getStartAndEndDate(DayType.TO_MONTH);
            if (day == null) {
                throw new BadRequestException("维度类型参数错误");
            }
            startDate = day.get("startDate");
            endDate = day.get("endDate");
        }
        AgentDTO agent = jwtUserDetailsService.getAgentInfo();
        Long channelId = agent.getChannelId();
        Long id = agent.getId();
        //获取合伙人id （直营+间接)
        List<Long> ziYingIds = new ArrayList<>();
        ziYingIds.add(id);
        List<Long> tuanDuiIds = agentContactService.findAllTeamIdsExceptSelf(id, channelId);
        List<Long> zhiShuIds = agentContactService.findDirectlyIds(id, channelId);
        List<Long> heHuoRenIds = agentContactService.findPartnerTeam(id, channelId);
        //查询数据
        TransactionSumVO self = transactionInfoService.queryTransactionSum(channelId, ziYingIds, startDate, endDate);
        TransactionSumVO team = transactionInfoService.queryTransactionSum(channelId, tuanDuiIds, startDate, endDate);
        TransactionSumVO direct = transactionInfoService.queryTransactionSum(channelId, zhiShuIds, startDate, endDate);
        TransactionSumVO partner = transactionInfoService.queryTransactionSum(channelId, heHuoRenIds, startDate, endDate);
        map.put("self", self); //自营
        map.put("team", team);//团队
        map.put("direct", direct);//直营
        map.put("partner", partner);//合伙人
        return map;
    }

    @Override
    public Map<String, Object> getExpandInfo() {
        Map<String, Object> map = new HashMap<>();
        AgentDTO agent = jwtUserDetailsService.getAgentInfo();
        Long id = agent.getId();
        String phone = agent.getPhone();
        Long channelId = agent.getChannelId();
        String name = "";
        //是否实名认证
        if (agent.getIsEffective() == 2) {
            AgentVerified verified = verifiedService.findById(id);
            name = verified.getCardName();
        } else {
            //截取手机号码后四位
            phone.substring(6, 10);
            name = "用户" + phone;
        }
        map.put("name", name);
        map.put("agentId", id);
        map.put("regisUrl", CommonConst.REGIS_URL + id + "/channelId/" + channelId);
        return map;
    }

    @Override
    public Map<String, Object> getAddMerchantList(DateTypeDTO dto) {
        Map<String, Object> map = new HashMap<>();
        AgentDTO agent = jwtUserDetailsService.getAgentInfo();
        Long id = agent.getId();
        Long channelId = agent.getChannelId();
        String endDate = dto.getEndDate();
        String startDate = dto.getStartDate();
        if (StringUtils.isBlank(endDate) || StringUtils.isBlank(startDate)) {
            //默认本月时间
            Map<String, String> day = DateStrUtils.getStartAndEndDate(DayType.TO_MONTH);
            if (day == null) {
                throw new BadRequestException("维度类型参数错误");
            }
            startDate = day.get("startDate");
            endDate = day.get("endDate");
        }
        //自营 直营 合伙人
        List<MerchantType> list = MerchantType.getMerchantTypeList();
        for (int i = 0; i < list.size(); i++) {
            List<Long> ids = new ArrayList<>();
            String type = list.get(i).getType();
            switch (type) {
                case "self":
                    ids.add(id);
                    break;
                case "partner":
                    ids = agentContactService.findPartnerTeam(id, channelId);
                    break;
                case "direct":
                    ids = agentContactService.findDirectlyIds(id, channelId);
                    break;
            }
            QuerTypePageDTO query = new QuerTypePageDTO();
            query.setChannelId(channelId);
            query.setEndDate(endDate);
            query.setIds(ids);
            query.setPageNum(0);
            query.setStartDate(startDate);
            query.setPageSize(5);
            JpaPageHelper page = merchantService.queryAddMerchantList(query);
            list.get(i).setList(page.getResult());
            int totalCount = merchantService.queryTotalTerminalCount(ids, startDate, endDate);
            list.get(i).setTotalCount(totalCount);
        }
        map.put("list", list);
        return map;
    }

    @Override
    public Map<String, Object> getAddMerchantPage(QueryPageDateTypeDTO dto) {
        Map<String, Object> map = new HashMap<>();
        //获取登录人id
        AgentDTO agent = jwtUserDetailsService.getAgentInfo();
        Long channelId = agent.getChannelId();
        Long id = agent.getId();
        //开始时间  结束时间
        String startDate = dto.getStartDate();
        String endDate = dto.getEndDate();
        if (StringUtils.isBlank(endDate) || StringUtils.isBlank(startDate)) {
            //默认本月时间
            Map<String, String> day = DateStrUtils.getStartAndEndDate(DayType.TO_MONTH);
            if (day == null) {
                throw new BadRequestException("维度类型参数错误");
            }
            startDate = day.get("startDate");
            endDate = day.get("endDate");
        }
        String type = dto.getType();
        int pageNum = dto.getPageNum();
        int pageSize = dto.getPageSize();
        List<Long> ids = new ArrayList<>();
        switch (type) {
            case "self":
                ids.add(id);
                break;
            case "partner":
                ids = agentContactService.findPartnerTeam(id, channelId);
                break;
            case "direct":
                ids = agentContactService.findDirectlyIds(id, channelId);
                break;
        }
        //封装参数
        QuerTypePageDTO query = new QuerTypePageDTO();
        query.setChannelId(channelId);
        query.setEndDate(endDate);
        query.setIds(ids);
        query.setPageNum(pageNum);
        query.setStartDate(startDate);
        query.setPageSize(pageSize);
        JpaPageHelper page = merchantService.queryAddMerchantList(query);
        map.put("page", page);
        return map;
    }

    @Override
    public Map<String, Object> getAddMerchantInfoList(AddMerchantInfoDTO dto) {
        Map<String, Object> map = new HashMap<>();
        AgentDTO agent = jwtUserDetailsService.getAgentInfo();
        Long id = agent.getId();
        Long channelId = agent.getChannelId();
        String endDate = dto.getEndDate();
        String startDate = dto.getStartDate();
        Long terminalTypeId = dto.getTerminalTypeId();
        String types = dto.getTypes();
        List<Long> ids = new ArrayList<>();
        if ("self".equals(types)) {
            ids.add(id);
        } else if ("direct".equals(types)) {
            ids = agentContactService.findDirectlyIds(id, channelId);
        } else if ("partner".equals(types)) {
            ids = agentContactService.findPartnerTeam(id, channelId);
        } else {
            throw new BadRequestException("查询条件错误");
        }
        List<QueryAddMerchantInfoListVO> list = merchantService.queryAddMerchantInfoList(ids, startDate, endDate, terminalTypeId);
        map.put("list", list);
        return map;
    }

    @Override
    public Map<String, Object> getAddAgentList(DateTypeDTO dto) {
        Map<String, Object> map = new HashMap<>();
        AgentDTO agent = jwtUserDetailsService.getAgentInfo();
        Long id = agent.getId();
        String endDate = dto.getEndDate();
        String startDate = dto.getStartDate();
        Long channelId = agent.getChannelId();
        if (StringUtils.isBlank(endDate) || StringUtils.isBlank(startDate)) {
            //默认本月时间
            Map<String, String> day = DateStrUtils.getStartAndEndDate(DayType.TO_MONTH);
            if (day == null) {
                throw new BadRequestException("维度类型参数错误");
            }
            startDate = day.get("startDate");
            endDate = day.get("endDate");
        }
        //直营
        List<Long> directIds = agentContactService.findDirectlyIds(id, channelId);
        //团队
        List<Long> teamIds = agentContactService.findPartnerTeam(id, channelId);
        int directCount = agentService.queryCountByAgentIds(channelId, directIds, startDate, endDate);
        int teamCount = agentService.queryCountByAgentIds(channelId, teamIds, startDate, endDate);
        map.put("directCount", directCount);
        map.put("partnerCOunt", teamCount);
        return map;
    }

    @Override
    public Map<String, Object> getAddAgentInfoList(AddAgentInfoDTO dto) {
        Map<String, Object> map = new HashMap<>();
        AgentDTO agent = jwtUserDetailsService.getAgentInfo();
        Long id = agent.getId();
        Long channelId = agent.getChannelId();
        String endDate = dto.getEndDate();
        String startDate = dto.getStartDate();
        String types = dto.getTypes();
        List<Long> ids;
        //直营
        if ("direct".equals(types)) {
            ids = agentContactService.findDirectlyIds(id, channelId);
        } else if ("partner".equals(types)) {
            ids = agentContactService.findPartnerTeam(id, channelId);
        } else {
            throw new BadRequestException("查询条件错误");
        }
        if (StringUtils.isBlank(endDate) || StringUtils.isBlank(startDate)) {
            //默认本月时间
            Map<String, String> day = DateStrUtils.getStartAndEndDate(DayType.TO_MONTH);
            if (day == null) {
                throw new BadRequestException("维度类型参数错误");
            }
            startDate = day.get("startDate");
            endDate = day.get("endDate");
        }
        List<QueryAddAgentListVO> list = agentService.queryAddAgentList(ids, channelId, startDate, endDate);
        for (int i = 0; i < list.size(); i++) {
            Long agnetId = list.get(i).getAgentId();
            Long pidId = list.get(i).getPidId();
            //查询是否实名认证
            AgentVerified agnetVerified = agentVerifiedService.findById(agnetId);
            String pidName;
            if (pidId == 0) {
                pidName = "顶级用户";
            } else {
                AgentVerified pidVerified = agentVerifiedService.findById(pidId);
                pidName = pidVerified.getCardName();
            }
            list.get(i).setAgentName(agnetVerified.getCardName());
            list.get(i).setPidName(pidName);
        }
        map.put("list", list);
        return map;
    }

    /**
     * 业务
     */
    @Override
    public List<ChartVO> getYeWuCharList(String startDate, String endDate, Long agentId, Long channelId) {
        List<ChartVO> chartList = new ArrayList<>();

        List<Long> heHuoRenIds = agentContactService.findPartnerTeam(agentId, channelId);
        List<Long> zhiYinIds = agentContactService.findDirectlyIds(agentId, channelId);
        //分润
        String heHuoRenBenefit = benefitDayService.getBenefit(heHuoRenIds, startDate, endDate);
        String zhiYinBenefit = benefitDayService.getBenefit(zhiYinIds, startDate, endDate);
        ChartVO fenRun = getChart("分润", new String[]{"直营," + zhiYinBenefit, "合伙人," + heHuoRenBenefit});
        //激活率
        List<Long> jiHuoList = new ArrayList<>();
        jiHuoList.add(agentId);
        String weiJiHuo = terminalService.getActivationCount(jiHuoList, startDate, endDate, 0);
        String yiJiHuo = terminalService.getActivationCount(jiHuoList, startDate, endDate, 1);
        ChartVO jiHuoLv = getChart("激活率", new String[]{"已激活," + weiJiHuo, "未激活," + yiJiHuo});

        chartList.add(fenRun);
        chartList.add(jiHuoLv);
        return chartList;
    }

    /**
     * 团队
     */
    @Override
    public List<ChartVO> getTuanDuiCharList(String startDate, String endDate, Long agentId, Long channelId) {
        List<ChartVO> chartList = new ArrayList<>();

        List<Long> heHuoRenIds = agentContactService.findPartnerTeam(agentId, channelId);
        List<Long> zhiYinIds = agentContactService.findDirectlyIds(agentId, channelId);
        //团队组成
        ChartVO tuanDui = getChart("团队组成", new String[]{"直营," + zhiYinIds.size(), "合伙人," + heHuoRenIds.size()});
        //已激活率
        String heHuoRenCount = terminalService.getActivationCount(heHuoRenIds, startDate, endDate, 1);
        String zhiYinCount = terminalService.getActivationCount(zhiYinIds, startDate, endDate, 1);
        ChartVO yiJiHuoLv = getChart("激活率", new String[]{"直营," + zhiYinCount, "合伙人," + heHuoRenCount});
        //台均
        String zhiYin = terminalService.getAverageSum(zhiYinIds, startDate, endDate, channelId);
        String heHuoRen = terminalService.getAverageSum(heHuoRenIds, startDate, endDate, channelId);
        ChartVO taiJun = getChart("台均", new String[]{"直营," + zhiYin, "合伙人," + heHuoRen});
        //分润
        String heHuoRenBenefit = benefitDayService.getBenefit(heHuoRenIds, startDate, endDate);
        String zhiYinBenefit = benefitDayService.getBenefit(zhiYinIds, startDate, endDate);
        ChartVO fenRun = getChart("分润", new String[]{"直营," + zhiYinBenefit, "合伙人," + heHuoRenBenefit});
        chartList.add(tuanDui);
        chartList.add(yiJiHuoLv);
        chartList.add(taiJun);
        chartList.add(fenRun);
        return chartList;
    }

    /**
     * 设备
     */
    @Override
    public List<ChartVO> getSheBeiCharList(String startDate, String endDate, Long agentId, Long channelId) {
        List<ChartVO> chartList = new ArrayList<>();
        List<Long> jiHuoList = new ArrayList<>();
        jiHuoList.add(agentId);
        String weiJiHuo = terminalService.getActivationCount(jiHuoList, startDate, endDate, 0);
        String yiJiHuo = terminalService.getActivationCount(jiHuoList, startDate, endDate, 1);
        ChartVO jiHuoShuLiang = getChart("激活数量", new String[]{"已激活," + weiJiHuo, "未激活," + yiJiHuo});
        chartList.add(jiHuoShuLiang);
        return chartList;
    }

    /**
     * 客户
     */
    @Override
    public List<ChartVO> getKeHuCharList(String startDate, String endDate, Long agentId, Long channelId) {
        List<ChartVO> chartList = new ArrayList<>();
        List<Long> tuanDuiIds = agentContactService.findAllTeamIds(agentId, channelId);
        List<Long> zhiYinIds = agentContactService.findDirectlyIds(agentId, channelId);
        //查询自营
        List<Long> ziYingId = new ArrayList<>();
        ziYingId.add(agentId);
        //用户组成、用户构成
        int tuanDui = merchantService.queryCountByAgentIds(tuanDuiIds, startDate, endDate);
        int zhiYing = merchantService.queryCountByAgentIds(zhiYinIds, startDate, endDate);
        int ziYing = merchantService.queryCountByAgentIds(ziYingId, startDate, endDate);
        ChartVO zuCheng = getChart("用户组成", new String[]{"自营," + ziYing, "团队," + tuanDui});
        ChartVO gouCheng = getChart("用户构成", new String[]{"直营," + zhiYing, "自营," + ziYing, "团队," + tuanDui});
        chartList.add(zuCheng);
        chartList.add(gouCheng);
        return chartList;
    }

    /**
     * 组装饼图最里面的值
     *
     * @param titles 数组[]
     * @return
     */
    public ChartVO getChart(String name, String[] titles) {
        List<ChartInfoVO> list = new ArrayList<>();
        //累加总和
        Float dividend = 0f;
        for (String title : titles) {
            String[] charInfo = title.split(",");
            dividend += Float.parseFloat(charInfo[1]);
        }
        for (String title : titles) {
            String[] charInfo = title.split(",");
            String rateName = charInfo[0];
            Float div = Float.parseFloat(charInfo[1]);
            NumberFormat numberFormat = NumberFormat.getInstance();
            // 设置精确到小数点后2位
            numberFormat.setMaximumFractionDigits(2);
            String result = numberFormat.format(div / dividend * 100);
            if (result.indexOf(".") != -1) {
                result = Math.round(Double.parseDouble(result)) + "";
            }
            if (Math.abs(dividend) < 0.0001) {
                result = "0";
            }
            ChartInfoVO vo = new ChartInfoVO(rateName, result);
            list.add(vo);
        }
        ChartVO chart = new ChartVO(name, list);
        return chart;
    }
}
